use crate::utils::constant::get_user_info_json_path;
use clap::builder::Str;
use log::error;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::fs::File;
use std::io;
use std::io::{Read, Write};

#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct UserInfo {
    pub login_type: String,
    pub token: String,
    pub nickname: String,
    pub account: String,
    pub uid: String,
    pub user_phone: String,
    pub create_time: String,
    pub username: String,
    pub check: String,
}

pub fn get_user_info() -> io::Result<Value> {
    let user_path = get_user_info_json_path();
    if !user_path.exists() {
        error!("请先登录");
        Err(io::Error::new(io::ErrorKind::NotFound, "请先登录"))
    } else {
        let mut user_file = File::options().read(true).open(user_path.as_path())?;
        let mut user_json = String::new();
        user_file
            .read_to_string(&mut user_json)
            .expect("读取用户信息失败");
        let user_info: Value = serde_json::from_str(&user_json)?;
        Ok(user_info)
    }
}

pub fn set_user_info(user_info: Value) -> io::Result<()> {
    let user_json = serde_json::to_string_pretty(&user_info)?;
    let user_path = get_user_info_json_path();
    let mut user_info_file = File::options()
        .write(true)
        .create(true)
        .open(user_path.as_path())?;
    user_info_file.write_all(user_json.as_bytes())?;
    user_info_file.flush()?;
    Ok(())
}
